import { defineStore } from 'pinia'
import { ref } from 'vue'
import { ElNotification } from 'element-plus'
import { Cloud } from 'laf-client-sdk'
const APPID = 'su75ks' // Laf 应用 appid
const cloud = new Cloud({
  baseUrl: `https://${APPID}.laf.run`,
  getAccessToken: () => '',
})

export const useUserStore = defineStore(
  'user',
  () => {
    //定义数据state
    const userInfo = ref({
      year: 1,
      status: '',
      period: '',
      outlook: '',
      branch_id: '',
    })
    const token = ref()
    const _id = ref()
    const name = ref()
    const utype = ref(1)
    const email = ref()
    const num = ref()
    const phone = ref()
    const branch_name = ref()
    const admin = ref()
    //定义获取接口数据的action函数
    //密码登录
    const loginByPw = async ({ email, password }) => {
      const res = await cloud.invoke('login', { email, password })
      if (res.code == 404) {
        ElNotification({
          message: res.error,
          type: 'error',
          duration: 3000,
        })
        return -1
      } else if (res.code == 200) {
        token.value = res.token
        return 1
      }
    }
    //验证码登录
    const loginByCode = async ({ email, verificationCode }) => {
      const res = await cloud.invoke('login_first_verify', { email, verificationCode })
      if (res.code == 404) {
        ElNotification({
          message: res.error,
          type: 'error',
          duration: 3000,
        })
        return -1
      } else if (res.code == 200) {
        token.value = res.token
        ElNotification({
          message: '请党员同志及时修改电话和登录密码,点击头像可见,初始密码为' + res.newpassword,
          type: 'success',
          duration: 0,
        })
        return 1
      }
    }
    //获取验证码
    const getLoginVerifyCode = async ({ email }) => {
      console.log(email)
      const res = await cloud.invoke('login_first_send', { email })
      if (res.code == 404) {
        ElNotification({
          message: res.error,
          type: 'error',
          duration: 3000,
        })
      } else if (res.code == 200) {
        ElNotification({
          message: res.message,
          type: 'success',
          duration: 3000,
        })
      }
    }
    //退出时清除用户信息
    const clearUserInfo = () => {
      userInfo.value = {
        year: 1,
        status: '',
        period: '',
        outlook: '',
        branch_id: '',
      }
      token.value = ''
      _id.value = ''
      name.value = ''
      utype.value = 1
      email.value = ''
      num.value = ''
      phone.value = ''
      branch_name.value = ''
      admin.value = ''
    }
    //导出数据
    return {
      token,
      _id,
      userInfo,
      email,
      num,
      name,
      utype,
      phone,
      branch_name,
      admin,
      loginByPw,
      getLoginVerifyCode,
      loginByCode,
      clearUserInfo,
    }
  },
  {
    persist: true,
  },
)
